package org.apache.solr.handler.dataimport.scheduler;

import java.text.SimpleDateFormat;
import java.util.Timer;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 监听器用于启动定时JOB
 * @author IMZHANGJIE.CN
 *
 */
public class ApplicationListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory.getLogger(ApplicationListener.class);

	@Override
	public void contextDestroyed(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();

		// get our timer from the context
		Timer timer = (Timer) servletContext.getAttribute("timer");
		Timer fullImportTimer = (Timer) servletContext
				.getAttribute("fullImportTimer");

		// cancel all active tasks in the timers queue
		if (timer != null)
			timer.cancel();
		if (fullImportTimer != null)
			fullImportTimer.cancel();

		// remove the timer from the context
		servletContext.removeAttribute("timer");
		servletContext.removeAttribute("fullImportTimer");

	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		ServletContext servletContext = servletContextEvent.getServletContext();
		logger.info("starting to init the task .......");
		try {
			// ######################################增量索引任务计划开始###################################
			// create the timer and timer task objects
			Timer timer = new Timer();
			DeltaImportHTTPPostScheduler task = new DeltaImportHTTPPostScheduler(servletContext.getServletContextName(), timer);

			// get our interval from HTTPPostScheduler
			int deltaBuildIndexInterval = task.getIntervalInt();

			// 到达开始时间会马上触发，然后再每隔一段时间执行一次
			timer.scheduleAtFixedRate(task, task.getBeginTime(), 1000 * deltaBuildIndexInterval);

			logger.info("delta import index task will first start at "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(task.getBeginTime()));
			
			// save the timer in context
			servletContext.setAttribute("timer", timer);
			//######################################增量索引任务计划结束###################################

			// #######################################重做索引任务计划开始########################################
			Timer fullImportTimer = new Timer();
			FullImportHTTPPostScheduler fullImportTask = new FullImportHTTPPostScheduler(servletContext.getServletContextName(), fullImportTimer);

			int reBuildIndexInterval = fullImportTask.getIntervalInt();
			if (reBuildIndexInterval <= 0) {
				logger.warn("Full Import Schedule disabled");
				return;
			}

			// schedule the task
			fullImportTimer.scheduleAtFixedRate(fullImportTask,fullImportTask.getBeginTime(), 1000 * reBuildIndexInterval);

			logger.info("full import index task will first start at "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(fullImportTask.getBeginTime()));
			
			// save the timer in context
			servletContext.setAttribute("fullImportTimer", fullImportTimer);
			// #######################################重做索引任务计划结束########################################
			
			// #######################################定期删除索引任务计划开始########################################
			Timer removeIndexTimer = new Timer();
			RemoveIndexHTTPPostScheduler removeIndexTask = new RemoveIndexHTTPPostScheduler(servletContext.getServletContextName(), removeIndexTimer);
			
			int removeIndexInterval = removeIndexTask.getIntervalInt();
			if(removeIndexInterval <= 0){
				logger.warn("Remove Index Schedule disabled");
				return;
			}
			
			removeIndexTimer.scheduleAtFixedRate(removeIndexTask, removeIndexTask.getBeginTime(), 1000*removeIndexInterval);
			
			logger.info("remove index task will first start at "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(removeIndexTask.getBeginTime()));
			// #######################################定期删除索引任务计划开始########################################
			
			// #######################################定期优化索引任务计划开始########################################
			Timer optimizedIndexTimer = new Timer();
			OptimizedIndexHTTPPostScheduler optimizedIndexTask = new OptimizedIndexHTTPPostScheduler(servletContext.getServletContextName(), optimizedIndexTimer);
			
			int optimizedIndexInterval = optimizedIndexTask.getIntervalInt();
			if(optimizedIndexInterval <= 0){
				logger.warn("Optimized Index Schedule disabled");
				return;
			}
			
			optimizedIndexTimer.scheduleAtFixedRate(optimizedIndexTask, optimizedIndexTask.getBeginTime(), 1000*optimizedIndexInterval);
			
			logger.info("Optimized index task will first start at "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(optimizedIndexTask.getBeginTime()));
			// #######################################定期优化索引任务计划开始########################################			
		} catch (Exception e) {
			if (e.getMessage().endsWith("disabled")) {
				logger.warn("Schedule disabled");
			} else {
				logger.error("Problem initializing the scheduled task: ", e);
			}
		}
		logger.info("init tasks over.......");
	}
	
	public static void main(String[] args) throws Exception {
		Timer timer = new Timer();
		DeltaImportHTTPPostScheduler task = new DeltaImportHTTPPostScheduler("solr", timer);

		// get our interval from HTTPPostScheduler
		int deltaBuildIndexInterval = task.getIntervalInt();

		// 到达开始时间会马上触发，然后再每隔一段时间执行一次
		timer.scheduleAtFixedRate(task, task.getBeginTime(), 1000 * deltaBuildIndexInterval);

	}

}